package com.uco.thread;

import lombok.AllArgsConstructor;
import lombok.Data;

public class ThreadSafe {
    public static void main(String[] args) {
        // 创建一个账户
        Account account = new Account("ID-001", 1000);
        System.out.println("账户创建成功");
        Thread xm = new Thread(() -> account.fetchBalance(1000));
        Thread xh = new Thread(() -> account.fetchBalance(1000));
        xm.start();
        xh.start();
    }
}

@Data
@AllArgsConstructor
class Account {
    private String id;
    private double balance;

    // 取款流程
    // 同步方法
    public synchronized void fetchBalance(double amount) {
        // 同步代码快
        synchronized ( this) {
        System.out.println(Thread.currentThread().getName() + " 开始取款流程");
        // 多个线程可能同时取款，导致线程安全问题
        if (balance >= amount) {
            balance -= amount;
            System.out.println(Thread.currentThread().getName() + " 取款成功，余额为：" + balance);
        } else {
            System.out.println("余额不足");
        }
        }
    }
}
